//
// Created by zzh on 2020/12/15.
//

#include "JavaCallback.h"
#include "macro.h"

JavaCallback::JavaCallback(JavaVM *vm, JNIEnv *env, jobject instance) {
    this->vm = vm;
    this->env = env;
    // 一旦涉及到jobject 跨方法 跨线程 就需要创建全局引用
    this->instance = env->NewGlobalRef(instance);
    //获取java对象
    jclass clazz = env->GetObjectClass(instance);
    errorMethodID = env->GetMethodID(clazz, "onFFmpegError", "(I)V");
    prepareMethodID = env->GetMethodID(clazz, "onFFmpegPrepared", "()V");
}

JavaCallback::~JavaCallback() {
    env->DeleteGlobalRef(instance);
}

/*
 * 错误回调
 * thread： THREAD_MAIN 1 主线程 ， THREAD_CHILD 2 子线程
 * errorCode：错误码
 **/
void JavaCallback::onError(int thread, int errorCode) {
    if (thread == THREAD_MAIN) {
        //主线程则直接调用方法
        env->CallVoidMethod(instance, errorMethodID, errorCode);
    } else if (thread == THREAD_CHILD) {
        //子线程，则先让c++线程附加到java线程
        JNIEnv *jniEnv;
        vm->AttachCurrentThread(&jniEnv, 0);
        jniEnv->CallVoidMethod(instance, errorMethodID, errorCode);
        vm->DetachCurrentThread();
    }
}

void JavaCallback::onPrepare(int thread) {
    if (thread == THREAD_MAIN) {
        //主线程则直接调用方法
        env->CallVoidMethod(instance, prepareMethodID);
    } else if (thread == THREAD_CHILD) {
        //子线程，则先让c++线程附加到java线程
        JNIEnv *jniEnv;
        vm->AttachCurrentThread(&jniEnv, 0);
        jniEnv->CallVoidMethod(instance, prepareMethodID);
        vm->DetachCurrentThread();
    }
}

